package com.google.cbmgraph;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.cbmgraph.data.DataSource;
import com.google.cbmgraph.data.DataSourceList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class SplashAnimation extends Activity {
	
	private static final String TAG = "SplashScreen";

	private static final int CONNECTION_TIMEOUT = 0;

	private static final int WAIT_RESPONSE_TIMEOUT = 0;
	

	private Thread mSplashThread; 
	
	public SplashAnimation() {

	}

	/** Called when the activity is first created. 
	 *
	 * onCreated originally written by Lee Periolat modified to load data from server
	 * 
	 * */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

        setContentView(R.layout.splash_animation);
        final DataSourceList dataNames = getDataNames();
        
        final SplashAnimation splashAnimation = this;   
        final ImageView splashImageView = (ImageView) findViewById(R.id.SplashImageView);
        splashImageView.setBackgroundResource(R.drawable.loading_animation);
        final AnimationDrawable frameAnimation = (AnimationDrawable)splashImageView.getBackground();
        
        splashImageView.post(new Runnable(){
            @Override
            public void run() {
                frameAnimation.start();                
            }            
        }); 
        
        mSplashThread =  new Thread(){
            @Override
            public void run(){
            	
                try {
                    synchronized(this){
                        // Wait given period of time or exit on touch
                        wait(2400);
                    }
                }
                catch(InterruptedException ex){                    
                }

                finish();
                
                // Run next activity
                Bundle b = new Bundle();
                b.putParcelable("datasourcelist", dataNames);
                Intent intent = new Intent();
                intent.setClass(splashAnimation, MainFragmentView.class);
                intent.putExtras(b);
                startActivity(intent);
                finish();               
            }
        };
        
        mSplashThread.start();    
    }
	/** Gets data names*/
	private DataSourceList getDataNames() {
		Log.d(TAG, "entered class");
	    String xml="";
	    try {
	    	Log.d(TAG, "setting parameters");
	    	HttpParams httpParameters = new BasicHttpParams();
	    	HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
	    	HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
	    	HttpConnectionParams.setTcpNoDelay(httpParameters, true);
	        HttpClient client = new DefaultHttpClient(httpParameters);
	        HttpGet request = new HttpGet();
	    	Log.d(TAG, "creating get request");
	        request.setURI(new URI(DataSource.URL+"?menu=true"));
	        HttpResponse response = client.execute(request);
	    	
            HttpEntity httpEntity = response.getEntity();
            xml = EntityUtils.toString(httpEntity);
            Log.d(TAG, "got response! "+ xml);
	    }catch (UnsupportedEncodingException e) {
            Log.d(TAG,e.toString());
        } catch (ClientProtocolException e) {
        	Log.d(TAG,e.toString());
        } catch (IOException e) {
        	Log.d(TAG,e.toString());
        } catch (URISyntaxException e) {
        	Log.d(TAG,e.toString());
		}
	    if (xml.length()>1){
	    	return parseXML(xml);
	    }else{
	    	Log.wtf("MASSIVE ERROR", "NO XML RETURNED");
	    	return null;
	    }
	}
	/** Parses xml into objects. */
	public static DataSourceList parseXML(String xmlData) {
		Document doc = getDomElement(xmlData);
		// data is separated by "doc" tags
		NodeList nl = doc.getElementsByTagName("datadoc");
		DataSourceList dataNames = new DataSourceList();
		for (int i = 0; i < nl.getLength(); i++){
			Element element = (Element)nl.item(i);
			String test = getElementValue(element);
			Log.d(TAG, "adding value: "+test);
			dataNames.add(test);
		}	
		return dataNames;
	}
	/** helper function for parsing XML */
	private static Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
 
            DocumentBuilder db = dbf.newDocumentBuilder();
 
            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);
 
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
                // return DOM
            return doc;
    }
	/** Helper function for parsing xml */
	private static final String getElementValue( Node elem ) {
		     Node child;
		     if( elem != null){
		         if (elem.hasChildNodes()){
		             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
		                 if( child.getNodeType() == Node.TEXT_NODE  ){
		                     return child.getNodeValue();
		                 }
		             }
		         }
		     }
		     return "";
	  }	

}
